Array.prototype.reduce = function (callback, initialValue) {
    for (let i = 0; i < this.length; i++) {
        if (!initialValue) {
            initialValue = callback(this[i], this[i + 1], i + 1, this)
            i++
        } else {
            initialValue = callback(initialValue, this[i], i, this)
        }
    }
    return initialValue
}

let arr = [1, 2, 3, 4, 5]
let count = arr.reduce((prev, curr, currentIndex, array) => {
    // console.log(prev,curr,currentIndex)
    return prev + curr
})

// console.log(count) //输出15

function sun(a, b) {
    return a + b
}

function len(str) {
    return str.length
}

function addPrefix(str) {
    return "$" + str
}

// let r = addPrefix(len(sun("1", 2)))
// console.log(r) //=> $2

// 实现一个方法，将上面的三个方法合并为一个方法
function compose(...fns) {
    // 接收参数
    return function (...args) {
        let lastFn = fns.pop()
        // reduceRight从右往左执行
        return fns.reduceRight((prev, curry) => {
            return curry(prev)
        }, lastFn(...args))
    }
}

function compose2(...fns){
    return fns.reduce((prev,curry)=>{
        return function (...args){
            return prev(curry(...args))
        }
    })
}

let final = compose2(addPrefix, len, sun)
let r = final('1', 2)
console.log(r)